package converts

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	"time"
)

// AuthToDataPacket auth信息转为dataPacket（包含token）
func AuthToDataPacket(authInfo dto.AuthInfo, expire time.Duration, jwtAuth interfaces.ItfJwtParser, others ...map[string]interface{}) (*dto.AuthDataPacket, error) {
	if expire == 0 {
		expire = time.Hour
	}
	expiredAt := time.Now().Add(expire)

	authData := dto.AuthDataPacket{
		Auth:      authInfo,
		ExpiredAt: expiredAt.Unix(),
	}

	extends := map[string]interface{}{}
	if others != nil {
		for _, arr := range others {
			for k, v := range arr {
				extends[k] = v
			}
		}
	}
	token, err := jwtAuth.GetToken(authData)
	authData.Token = token
	return &authData, err
}

// TokenToAuthDataPacket token转为解析为authPacket
func TokenToAuthDataPacket(token string, jwtAuth interfaces.ItfJwtParser) (*dto.AuthDataPacket, error) {
	if token == "" {
		return nil, fmt.Errorf("token is nil")
	}

	data := dto.AuthDataPacket{}

	err := jwtAuth.ParseToken(&data, token)
	if err != nil {
		return nil, fmt.Errorf("token is invalid")
	}

	if data.ExpiredAt <= time.Now().Unix() {
		return nil, fmt.Errorf("auth expired")
	}
	return &data, nil
}

func AdminConvertAuthInfo(ad *models.Admin) dto.AuthInfo {
	if ad.LastLogin == nil {
		t := time.Now()
		ad.LastLogin = &t
	}
	return dto.AuthInfo{
		Id:       ad.Id,
		Nickname: ad.Nickname,
		Account:  ad.Account,
		Avatar:   ad.Avatar,
		Status:   ad.Status,
		SaasId:   0,
		Extends: map[string]string{
			"email":      ad.Email,
			"last_ip":    ad.LastIp,
			"last_login": ad.LastLogin.String(),
			"is_root":    fmt.Sprint(ad.IsRoot),
		},
	}
}

func UserConvertAuthInfo(ad *models.User) dto.AuthInfo {
	if ad.LastLogin == nil {
		t := time.Now()
		ad.LastLogin = &t
	}
	return dto.AuthInfo{
		Id:       ad.Id,
		Nickname: ad.Nickname,
		Account:  ad.Account,
		Avatar:   ad.Avatar,
		Status:   ad.Status,
		SaasId:   0,
		Extends: map[string]string{
			"email":      ad.Email,
			"last_ip":    ad.LastIp,
			"last_login": ad.LastLogin.String(),
		},
	}
}
